<template>
  <div>
    <Modal v-model="showModal" title="批量上传图片" :fullscreen="true" :closable="true" @on-visible-change="onVisibleChange" footer-hide :mask-closable="false">

      <Spin size="large" fix v-if="loading"></Spin>

      <ui-uploaders @on-success="handleSuccess" />

      <div class="pls-form-item-label">
        <span>批量裁剪</span>
        <Poptip word-wrap placement="right" trigger="hover" width="240">
          <Icon type="md-help-circle" />
          <div class="pls-poptip" slot="content">
            <p>使用系统默认的裁剪规则~</p>
            <p>自定义设置一个裁剪规则~</p>
          </div>
        </Poptip>
        <Button type="info" style="margin-left:15px;" @click="onCropperImages">一键裁剪</Button>
        <Row style="width:500px;margin-left:15px;">
          裁剪设置：
          x:
          <InputNumber :max="9999" :min="1" v-model="defaultCropper.x"></InputNumber>
          y:
          <InputNumber :max="9999" :min="1" v-model="defaultCropper.y"></InputNumber>
          w:
          <InputNumber :max="9999" :min="1" v-model="defaultCropper.w"></InputNumber>
          h:
          <InputNumber :max="9999" :min="1" v-model="defaultCropper.h"></InputNumber>
        </Row>
        <Button type="info" style="margin-left:15px;" @click="onSortImages">一键排序</Button>
      </div>

      <div class="pls-form-item-control">
        <div class="pls-anchor-image-mode-list">
          <div class="pls-anchor-item" v-for="(item, index) in imagesList" :key="index">
            <div class="pls-anchor-cover">
              <img v-if="item.crop" :src="`${item.img_url}`+`?x-oss-process=image/crop,x_${item.cropType.x},y_${item.cropType.y},w_${item.cropType.w},h_${item.cropType.h}`" style="height:200px;" />
              <img v-else :src="item.img_url" style="height:200px;" />
            </div>
            <div class="pls-anchor-operation">
              <div :class="[{ disabled: index === 0 }]" :data-i="index" @click="onLeft">
                <Icon type="ios-arrow-back" />
              </div>
              <!-- <div :data-i="index" @click="onEditAnchor">
                <Icon type="ios-create-outline" />
              </div> -->
              <div :data-i="index" @click="onRmoveImage">
                <Icon type="ios-trash-outline" />
              </div>
              <div :class="[{ disabled: index === imagesList.length - 1 }]" :data-i="index" @click="onRight">
                <Icon type="ios-arrow-forward" />
              </div>
            </div>
            <div class="pls-anchor-title">{{ item.img_title }}</div>
          </div>

          <div class="pls-add-image-new" @click="onAddResourceImage">
            <Icon type="ios-add" size="56" color="#6af" />
            <span>选择素材图片</span>
          </div>
        </div>
        <!-- <div class="pls-form-item-tips">上传3-9张真实拍摄的图片，请勿上传与商品无关的图片。图片尺寸不低于750x750；比例建议：1:1、4:3、3:4</div> -->
      </div>

      <div class="ice-add-image-dialog-new__footer">
        <div class="ice-add-image-dialog-new__footer__limit"></div>
        <div class="ice-add-image-dialog-new__footer__operation">
          <Button type="primary" @click="onSubmit">导入到编辑器</Button>
          <Button @click="onHide">取消</Button>
        </div>
      </div>

    </Modal>

    <resource-add-image :show="resourceAddImageModal" @on-visible-change="onVisibleImageModal" @on-export="onExportResourceImage" :needCrop="false"></resource-add-image>

    <!-- <Modal v-model="showCropperModal" title="图片裁剪" footer-hide :mask-closable="false">
      <ui-cropper-image ref="UiCropperImage" @on-export="onCropperExport" @on-visible-change="onCropperChange" />
    </Modal> -->

  </div>
</template>

<script>
import UiUploaders from './UiUploaders.vue'
import ResourceAddImage from '@/components/ui/UiAddImage.vue'
// import UiCropperImage from './UiCropperImage.vue'

export default {
  name: 'ui-add-image',
  components: {
    UiUploaders,
    ResourceAddImage,
    // UiCropperImage,
  },
  props: {
    show: Boolean,
    needCrop: Boolean,
    images: {
      type: Array,
      default () {
        return []
      }
    },
  },
  watch: {
    show (newVal, oldVal) {
      if (newVal !== oldVal) {
        this.showModal = newVal
      }
    }
  },
  data () {
    return {
      loading: false,
      stepCropper: false,
      showModal: false,

      defaultCropper: {
        x: 140,
        y: 110,
        w: 1000,
        h: 1600,
      },

      imagesList: [
        // {
        //   img_title: "15323075204286802.jpg",
        //   img_url: "https://img.soyul.cn/respicture/1/1/202012061808019203.jpg",
        //   img_width: 400,
        //   img_height: 400,
        // },
      ],

      // 添加素材图片弹窗
      resourceAddImageModal: false,

      // 图片裁剪
      showCropperModal: false,
      imageEditIndex: 0,

      CropType: '11',
      pickerSelectesImgs: [],
      minWidth: 0,
      minHeight: 0,
    }
  },
  methods: {
    // ######################################################################################################################
    // # 图片裁剪
    // ######################################################################################################################

    // 图片裁剪
    onEditAnchor (e) {
      const { i } = e.currentTarget.dataset
      this.imageEditIndex = e.currentTarget.getAttribute('data-i')
      this.pickerSelectesImgs = []
      this.pickerSelectesImgs = [this.imagesList[i]]
      this.$refs['UiCropperImage'].init(this.pickerSelectesImgs)
      this.showCropperModal = true
    },
    // 导出裁剪的图片
    onCropperExport (res) {
      const { images } = res
      const data = images[0]
      let img = this.imagesList[this.imageEditIndex]
      let thisImage = {
        ...img,
        crop: true,
        cropType: {
          x: data.x,
          y: data.y,
          w: data.w,
          h: data.h,
        }
      }
      this.imagesList[this.imageEditIndex] = thisImage
      this.imageEditIndex = 0
    },
    onCropperChange (res) {
      this.showCropperModal = res
    },



    // ######################################################################################################################






    // ######################################################################################################################
    // # 基本操作
    // ######################################################################################################################

    // 导出图片
    onSubmit () {
      this.$emit('on-export', this.imagesList)
      this.onHide()
    },
    // 上传成功添加图片回调
    handleSuccess (res) {
      const { data } = res
      let imgRes = {
        img_title: data.img_title,
        img_url: data.img_url,
        img_width: parseInt(data.img_width),
        img_height: parseInt(data.img_height),
        crop: false,
        cropType: [],
      }
      this.imagesList.push(imgRes)
    },
    onHide () {
      this.$emit('on-visible-change', false)
    },
    onVisibleChange (res) {
      this.showModal = res
    },
    // ######################################################################################################################





    // ######################################################################################################################
    // # 图片列表 操作方法
    // ######################################################################################################################

    // 删除图片
    onRmoveImage (e) {
      const { i } = e.currentTarget.dataset
      this.$Modal.confirm({
        title: '删除提醒',
        content: `确认删除此图片吗？`,
        onOk: () => {
          this.imagesList = this.imagesList
            .filter((item, index) => index !== Number(i))
            .map((item, index) => ({
              ...item,
              i: index
            }))
        }
      })
    },
    // 图片左移
    onLeft (e) {
      const { i } = e.currentTarget.dataset
      const index = Number(i)
      if (index === 0) return
      const cur = this.imagesList[index]
      const pre = this.imagesList[index - 1]
      this.$set(this.imagesList, index - 1, {
        ...cur,
        i: index - 1
      })
      this.$set(this.imagesList, index, {
        ...pre,
        i: index
      })
    },
    // 图片右移
    onRight (e) {
      const { i } = e.currentTarget.dataset
      const index = Number(i)
      if (index === this.imagesList.length - 1) return
      const cur = this.imagesList[index]
      const next = this.imagesList[index + 1]
      this.$set(this.imagesList, index + 1, {
        ...cur,
        i: index + 1
      })
      this.$set(this.imagesList, index, {
        ...next,
        i: index
      })
    },
    // 设置批量裁剪
    onCropperImages () {
      this.imagesList = this.imagesList.map(item => {
        item.crop = true
        item.cropType = this.defaultCropper
        return item
      })
    },
    // 一键排序
    onSortImages () {
      this.imagesList.sort(this.SortLikeWin)
    },
    // 模仿win排序
    SortLikeWin (v1, v2) {
      var a = v1.img_title;
      var b = v2.img_title;
      var reg = /[0-9]+/g;
      var lista = a.match(reg);
      var listb = b.match(reg);
      if (!lista || !listb) {
        return a.localeCompare(b);
      }
      for (var i = 0, minLen = Math.min(lista.length, listb.length); i < minLen; i++) {
        //数字所在位置序号
        var indexa = a.indexOf(lista[i]);
        var indexb = b.indexOf(listb[i]);
        //数字前面的前缀
        var prefixa = a.substring(0, indexa);
        var prefixb = b.substring(0, indexb);
        //数字的string
        var stra = lista[i];
        var strb = listb[i];
        //数字的值
        var numa = parseInt(stra);
        var numb = parseInt(strb);
        //如果数字的序号不等或前缀不等，属于前缀不同的情况，直接比较
        if (indexa != indexb || prefixa != prefixb) {
          return a.localeCompare(b);
        }
        else {
          //数字的string全等
          if (stra === strb) {
            //如果是最后一个数字，比较数字的后缀
            if (i == minLen - 1) {
              return a.substring(indexa).localeCompare(b.substring(indexb));
            }
            //如果不是最后一个数字，则循环跳转到下一个数字，并去掉前面相同的部分
            else {
              a = a.substring(indexa + stra.length);
              b = b.substring(indexa + stra.length);
            }
          }
          //如果数字的string不全等，但值相等
          else if (numa == numb) {
            //直接比较数字前缀0的个数，多的更小
            return strb.lastIndexOf(numb + '') - stra.lastIndexOf(numa + '');
          }
          else {
            //如果数字不等，直接比较数字大小
            return numa - numb;
          }
        }
      }
    },
    // ######################################################################################################################





    // ######################################################################################################################
    // # 添加素材图片
    // ######################################################################################################################

    // 添加素材图片 弹窗
    onAddResourceImage () {
      this.resourceAddImageModal = true
    },
    // 关闭素材图片 弹窗
    onVisibleImageModal (res) {
      this.resourceAddImageModal = res
    },
    // 导出素材图片
    onExportResourceImage (res) {
      const { images } = res
      const data = images[0]

      let crop = false
      let cropType = []
      // if (1) {
      //   crop = true
      //   cropType = {
      //     x: data.x,
      //     y: data.y,
      //     w: data.w,
      //     h: data.h,
      //   }
      // }

      let imgRes = {
        img_title: data.title,
        img_url: data.img_url,
        img_width: data.img_width,
        img_height: data.img_height,
        crop: crop,
        cropType: cropType,
      }

      this.resourceAddImageModal = false



      this.imagesList.push(imgRes)
    },
    // ######################################################################################################################







  },

}
</script>
<style lang="scss">
.iai-add-image__picture-sidebar {
  width: 140px;
  flex: 0 0 140px;
  overflow-y: auto;
  .ivu-menu-item-group-title {
    padding-left: 12px;
  }
}
.ice-add-image-dialog-new__footer__operation {
  display: flex;
  .ivu-btn {
    & + .ivu-btn {
      margin-left: 8px;
    }
  }
}
</style>
<style lang="scss" scoped>
.iai-add-image__picture-center {
  display: flex;
  height: 460px;
  border: 1px solid #e7e7e7;
}
.iai-add-image__picture-sidebar {
  width: 140px;
  flex: 0 0 140px;
  overflow-y: auto;
  .ivu-menu {
    height: 100%;
  }
}
.iai-add-image__picture-main {
  flex: 1;
}
.iai-add-image__picture-pagination {
  display: flex;
  justify-content: flex-end;
  padding: 12px 0;
}
.ice-any-picker {
  height: 410px;
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;
}
.ice-any-picker__trigger {
  margin-left: 12px;
  padding-bottom: 12px;
  position: relative;
}
.iai-add-image__resource-pic {
  width: 145px;
  height: 190px;
  border: 1px solid #e7e7e7;
}
.iai-add-image__resource-pic__cover {
  height: 143px;
  width: 143px;
  overflow: hidden;
  img {
    max-width: 100%;
    max-height: 100%;
    opacity: 1;
    vertical-align: middle;
  }
}
.iai-add-image__resource-pic__title {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  padding: 0 10px;
  line-height: 20px;
  padding-top: 5px;
}
.iai-add-image__resource-pic__pix {
  font-size: 12px;
  color: #999;
  padding: 0 10px;
  line-height: 20px;
}
.ice-any-picker__trigger-btn {
  width: 143px;
  height: 143px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  top: 0;
  left: 0;
  cursor: pointer;
  text-align: center;
  color: #fff;
  .ivu-icon {
    font-size: 28px;
    font-weight: bold;
    visibility: hidden;
  }
}
.ice-any-picker__trigger-btn-checked {
  background-color: rgba(#000, 0.5);
  .ivu-icon {
    visibility: visible;
  }
}

.ice-any-picker__trigger-btn-unavailable {
  width: 143px;
  height: 143px;
  line-height: 143px;
  background-color: rgba(255, 255, 255, 0.7);
  cursor: not-allowed;
  span {
    font-size: 18px;
    color: #666;
  }
}
</style>

<style lang="scss" scoped>
.cropper-export {
  display: flex;
}
.cropper-export-item {
  width: 300px;
  height: 300px;
}

.ui-publish--wrap {
  width: 100%;
  background-color: #fff;
  margin: 0 auto;
}

.pls {
  width: 100%;
  display: flex;
  line-height: 1;
}
.pls-container {
  flex: 1;
  padding: 45px 60px;
}

.pls-form-item {
  margin-bottom: 20px;
}
.pls-form-item-label {
  display: flex;
  align-items: center;
  padding: 12px 0;
}
.pls-form-item-required {
  .pls-form-item-label {
    &::before {
      content: '*';
      margin-right: 4px;
      line-height: 1;
      font-family: SimSun;
      font-size: 14px;
      color: #ed4014;
    }
  }
}
.pls-form-item-label span {
  margin-right: 6px;
}
.pls-form-item-label {
  .ivu-icon {
    font-size: 18px;
  }
}
.pls-anchor-image-mode-list {
  display: flex;
  flex-wrap: wrap;
}
.pls-anchor-item {
  position: relative;
  width: 200px;
  height: 200px;
  margin-right: 15px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(#ececec, 0.7);
}
.pls-anchor-cover {
  width: 200px;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid rgb(231, 231, 235);
  img {
    max-width: 100%;
    max-height: 100%;
  }
}
.pls-anchor-list {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
.pls-anchor-operation {
  width: 100%;
  height: 30px;
  position: absolute;
  left: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1;
  display: flex;
  > div {
    height: 100%;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #fff;
    cursor: pointer;
    &.disabled {
      cursor: default;
      color: #999;
    }
    & + div {
      border-left: #fff solid 1px;
    }
  }
}
.pls-anchor-title {
  width: 100%;
  height: 28px;
  position: absolute;
  left: 0;
  bottom: 30px;
  z-index: 1;
  display: flex;
  justify-content: center;
  > div {
    height: 100%;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #fff;
    cursor: pointer;
    &.disabled {
      cursor: default;
      color: #999;
    }
    & + div {
      border-left: #fff solid 1px;
    }
  }
}

.pls-face-image-list {
  display: flex;
  flex-wrap: wrap;
}
.pls-face-item {
  width: 134px;
  height: 134px;
  position: relative;
  margin-bottom: 15px;
  img {
    max-width: 100%;
    max-height: 100%;
  }
  &:hover {
    .pls-face-operation {
      display: flex;
    }
  }
}
.pls-face-operation {
  width: 100%;
  height: 24px;
  position: absolute;
  left: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 1;
  display: none;
  > div {
    height: 100%;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    color: #fff;
    cursor: pointer;
    & + div {
      border-left: #fff solid 1px;
    }
  }
}
</style>
